import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.junit.Test;

import java.io.*;

public class Poi_Demo {
    @Test
    public void test1() throws IOException {
//        创建工作簿
        XSSFWorkbook wokebook = new XSSFWorkbook(new FileInputStream(new File("D:\\test.xlsx")));
//       获取工作表
        XSSFSheet sheet = wokebook.getSheetAt(0);
//        便利获取工作表行对象
        for (Row row : sheet) {
//            遍历工作表行，获取单元格对象
            for (Cell cell : row) {
//                获取单元格中的值
                String value = cell.getStringCellValue();
                System.out.println(value);
            }
        }
        wokebook.close();
    }

    @Test
    public void test2() throws Exception{
        XSSFWorkbook workbook = new XSSFWorkbook(new FileInputStream(new File("D:\\test.xlsx")));
        XSSFSheet sheet = workbook.getSheet("Sheet1");
//        lastRowNum行的值是从0开始
        int lastRowNum = sheet.getLastRowNum();
        for (int i=0;i<=lastRowNum;i++){
            XSSFRow row = sheet.getRow(i);
//            单元格的值是从1开始
            short lastCellNum = row.getLastCellNum();
            for(short j=0;j<lastCellNum;j++){
                String value = row.getCell(j).getStringCellValue();
                System.out.println(value);
            }
        }
    }
    @Test
    public void test3()throws Exception{
        /*
        *创建workbook 从内存写入到磁盘
        * */
//        1.创建一个Excel文件
        XSSFWorkbook workbook = new XSSFWorkbook();
//        2.创建工作表
        XSSFSheet sheet = workbook.createSheet("传智播客");
//        创建行0表示第一行
        XSSFRow row = sheet.createRow(0);
        row.createCell(0).setCellValue("编号");
        row.createCell(1).setCellValue("姓名");
        row.createCell(2).setCellValue("年龄");
//        创建第二行
        XSSFRow row1 = sheet.createRow(1);
        row1.createCell(0).setCellValue("0001");
        row1.createCell(1).setCellValue("欧阳菲艳");
        row1.createCell(2).setCellValue("16");

        FileOutputStream fos = new FileOutputStream(new File("D:\\student.xlsx"));
//        通过输出流将Excel对象写入磁盘
        workbook.write(fos);
        fos.flush();
        fos.close();
        workbook.close();
    }
}
